﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCServer.Entities.Commands;
using IRCServer.Utilities;
using IRCServer.Entities;
using IRCServer.Backend;
using IRC.Utilities;

namespace IRCServer.CommandHandlers
{
    class PRIVMSGCommandHandler : CommandHandlerBase
    {
        public override string HandleCommand(IRCCommandBase command, SessionBase session)
        {
            if (command is PRIVMSGCommand)
            {
                PRIVMSGCommand privmsgCommand = (PRIVMSGCommand)command;

                if (privmsgCommand.Targets == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NORECIPIENT, command.CommandName());
                }

                if (privmsgCommand.Message == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NOTEXTTOSEND, string.Empty);
                }

                foreach (string target in privmsgCommand.Targets)
                {
                    List<User> filteredUsers = ServerBackend.Instance.Users.Where(u => u.Nickname.ToLower() == target.ToLower()).ToList();
                    if (filteredUsers.Count == 0)
                    {
                        ClientSession clientSession=(ClientSession)session;
                        string message= string.Format("{0} {1} {2} :{3}","SPRIVMSG", clientSession.User.Nickname,target,privmsgCommand.Message);
                        SPRIVMSGCommand serverPRVMSGCommand = new SPRIVMSGCommand(message);
                        serverPRVMSGCommand.ExecuteCommand(session);
                    }
                    else
                    {
                        ClientSession destination = (ClientSession)session;
                        string message = string.Format(":{0} {1} :{2}", destination.User.Nickname, privmsgCommand.CommandName(), privmsgCommand.Message);
                        
                        Logger.Instance.Info(string.Format("Sending {0} to {1}", message, target));

                        byte[] messageData = System.Text.Encoding.ASCII.GetBytes(message);
                        destination.Socket.BeginSend(messageData, 0, messageData.Length, System.Net.Sockets.SocketFlags.None, new AsyncCallback(FinalizeSending), destination);
                    }
                }

                return String.Empty;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        private void FinalizeSending(IAsyncResult result)
        {
            ClientSession session = (ClientSession)result.AsyncState;
            session.Socket.EndSend(result);
        }
    }
}
